<template>
  <j-modal :visible="modalVisible" :width="1000" @ok="handleOk" @cancel="handleCancel">
    <!-- 标题 -->
    <div style="display: flex;margin-bottom: 20px;">
      <a-input placeholder="请输入名称" style="width: 30%;" v-model="fileName" />
      <a-button type="primary" @click="handleSearch" style="margin: 0 15px;"><a-icon type="search" />搜索</a-button>
      <a-button type="primary" @click="addFile" style="margin: 0 15px;" v-if="showAddBtn">
        <a-icon type="folder-add" />新建文件夹</a-button
      >
      <a-button type="primary" icon="cloud-upload" @click="clickUpload" v-if="showAddBtn">上传文件</a-button>
    </div>
    <!-- 文件部分 -->
    <div>
      <a-breadcrumb separator=">">
        <a-breadcrumb-item v-for="(item, index) in breadcrumb" :key="index" href="">
          <span @click="goToFile(item.name)">
            <template v-if="item.icon"> <a-icon :type="item.icon"/></template>
            {{ item.name }}
          </span>
        </a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div style="display: flex;margin-top: 20px;flex-wrap: wrap;">
      <template v-if="currentData.length > 0">
        <!-- <contextmenu :itemList="menuItemList" :visible.sync="menuVisible" style="z-index: 9999;"> -->
        <div
          v-for="(item2, index2) in currentData"
          :key="index2"
          :class="['file', item2.selected ? 'fileSelected' : '']"
          @click="fileDetail(item2.type, item2.path, item2.id, item2.name, index2)"
        >
          <template v-if="item2.selected">
            <div class="selectIcon">
              <a-icon type="check-circle" style="color: green" />
            </div>
          </template>
          <img :src="getIcon(item2.type, item2.path)" style="width: 60px; height: 60px;" />
          <div>
            {{ item2.name }}
          </div>
        </div>
        <!-- </contextmenu> -->
      </template>

      <template v-else>
        <div style="width: 962px;text-align: center;">
          <img src="~@/assets/nodata.png" style="width: 600px;" />
        </div>
      </template>
    </div>
    <a-modal
      title="上传文件"
      :visible="fileVisible"
      :confirm-loading="uploadconfirmLoading"
      @ok="handleUpload"
      @cancel="handleCancelupload"
    >
      <a-upload-dragger
        name="file"
        :multiple="false"
        action="http://localhost:8080/jeecg-boot/rsfile/rsFile/add"
        method="post"
        :data="uploadData"
        :headers="uphearder"
        :remove="handleRemove"
        @change="handleChange"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击或拖拽文件上传
        </p>
        <p class="ant-upload-hint">
          暂仅支持单个文件上传
        </p>
      </a-upload-dragger>
    </a-modal>
    <a-modal :visible="createFolderVisible" @ok="handleFolderCreate" @cancel="cancelFolderCreate">
      <a-input placeholder="请输入文件夹名称" style="width: 90%;" v-model="folderName" />
    </a-modal>
  </j-modal>
</template>

<script>
import { getFileList, creatFolder } from '@/api/file'
import floderImg from '@/assets/fileimage/folder.png'
import filePdf from '@/assets/fileimage/pdf.png'
import mp4 from '@/assets/fileimage/mp4.png'
import fileImg from '@/assets/fileimage/file.png'
import { duration } from 'moment'
export default {
  name: 'fileDialog',
  props: {
    modalVisible: {
      type: Boolean,
      default: false
    },
    fileType: {
      type: String,
      default: 'video/mp4'
    }
  },
  data() {
    return {
      breadcrumb: [
        {
          name: '文件主目录',
          icon: 'home',
          id: 0,
          data: []
        }
      ],
      uphearder:{
          'tenant-id': JSON.parse(localStorage.getItem("pro__TENANT_ID")).value
        },
      currentData: [],
      fileName: '',
      folderName: '',
      showAddBtn: true,
      fileid: 0,
      // 选择文件的路径
      filePath: '',
      fileVisible: false,
      // 创建文件夹
      createFolderVisible: false,
      //上传文件确认加载
      uploadconfirmLoading: false,
      //上传的文件
      uploadFileList: [],
      uploadData: {},
      imageList: [
        {
          type: 'folder',
          src: floderImg
        },
        {
          type: 'application/pdf',
          src: filePdf
        },
        {
          type: 'video/mp4',
          src: mp4
        }
      ]
    }
  },
  methods: {
    handleOk() {
      const path = this.filePath;
      let duration = null;
      const _this = this;
      if (this.fileType === 'video/mp4') {
        const audio = new Audio(path)
        // 元数据已加载
        audio.addEventListener('loadedmetadata', function(e) {
         duration = Math.floor(audio.duration)
         _this.$emit('ok', path,duration)
        })
      }else{
        _this.$emit('ok', path)
      }
    },

    handleCancel() {
      this.$emit('cancel')
    },
    getIcon(fileType, filePath) {
      const isImage = fileType.split('/')[0] === 'image'
      if (isImage) {
        return filePath
      } else {
        const item = this.imageList.find(item => item.type === fileType)
        return item ? item.src : fileImg
      }
    },

    handleRemove(file) {
      const index = this.uploadFileList.indexOf(file)
      const newFileList = this.uploadFileList.slice()
      newFileList.splice(index, 1)
      this.uploadFileList = newFileList
    },
    //上传状态
    async handleChange(info) {
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        // this.fileVisible = false
        this.isCreateFile = false
        await this.updateData()
        info.fileList = []
        this.$message.success(`${info.file.name} 上传成功.`)
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
    },
    async updateData() {
      const res = await getFileList({
        id: this.fileid,
        fileType: this.fileType
      })
      const index = this.breadcrumb.findIndex(item => item.id === this.fileid)
      const data = res.result.map(item => {
        return {
          ...item,
          selected: false
        }
      })
      this.breadcrumb[index].data = data
      this.currentData = data
    },
    clickUpload() {
      this.fileVisible = true
      this.uploadData = {
        folderId: this.fileid,
        userId: JSON.parse(window.localStorage.getItem('pro__Login_Userinfo')).value.id,
        remark: '上传文件'
      }
    },
    // 去往指定目录
    goToFile(name) {
      const index = this.breadcrumb.findIndex(item => item.name === name)
      if (this.breadcrumb[index].id === -1) {
        this.showAddBtn = false
      } else {
        this.showAddBtn = true
      }
      this.breadcrumb = this.breadcrumb.slice(0, index + 1)
      this.currentData = this.breadcrumb[index].data
      this.fileid = this.breadcrumb[index].id
    },

    //预览文件
    async fileDetail(fileType, filePath, id, name, index) {
      if (fileType == 'folder') {
        this.currentData.forEach(item => {
          item.selected = false
        })
        const res = await getFileList({
          id: id,
          fileType: this.fileType
        })
        this.fileid = id
        this.showAddBtn = true
        const data = res.result.map(item => {
          return {
            ...item,
            selected: false
          }
        })
        this.currentData = data
        this.breadcrumb.push({
          name: name,
          id: id,
          data: data
        })
      } else {
        this.currentData.forEach(item => {
          item.selected = false
        })
        this.currentData[index].selected = true
        this.filePath = filePath
        // window.open(filePath, '_blank')
      }
    },
    //上传文件弹窗取消
    handleCancelupload() {
      this.uploadFileList = []
      this.fileVisible = false
    },
    handleUpload() {
      this.fileVisible = false
    },
    async handleSearch() {
      const index = this.breadcrumb.findIndex(item => item.name === this.fileName)
      if (index === -1) {
        const res = await getFileList({
          name: this.fileName,
          fileType: this.fileType
        })
        const data = res.result.map(item => {
          return {
            ...item,
            selected: false
          }
        })
        this.breadcrumb.push({
          name: this.fileName,
          id: -1,
          data: data
        })
        this.showAddBtn = false
        this.currentData = data
      } else {
        return this.$message.info('已存在搜索结果,请勿重复搜索！')
      }
    },
    addFile() {
      this.createFolderVisible = true
    },
    async handleFolderCreate() {
      if (this.folderName === '') {
        return this.$message.error('文件夹名称不能为空')
      } else {
        const res = await creatFolder({
          name: this.folderName,
          pid: this.fileid,
          userId: JSON.parse(window.localStorage.getItem('pro__Login_Userinfo')).value.id,
          remark: ''
        })

        if (res.code !== 200) {
          return this.$message.error('服务器内部错误')
        } else {
          await this.updateData()
          this.folderName = ''
          this.$message.success('文件夹创建成功')
          this.createFolderVisible = false
        }
      }
    },
    cancelFolderCreate() {
      this.createFolderVisible = false
    }
  },
  watch: {
    fileType: {
      async handler(val) {
        const res = await getFileList({
          id: 0,
          fileType: val
        })
        const data = res.result.map(item => {
          return {
            ...item,
            selected: false
          }
        })
        this.currentData = data
        this.breadcrumb[0].data = data
      }
    }
  }
}
</script>
<style scoped lang="less">
.file {
  display: flex;
  position: relative;
  padding: 5px;
  flex-wrap: wrap;
  width: 120px;
  height: 140px;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  &:hover {
    background-color: #eeeeee;
  }
  .selectIcon {
    position: absolute;
    top: 5px;
    left: 5px;
  }
  div {
    max-width: 90px;
    text-align: justify;
  }
}
.fileSelected {
  background-color: #eeeeee;
}
</style>
